<?php

namespace frontend\modules\dynamic\models;

use Yii;
use yii\data\ActiveDataProvider;
use yii\db\Exception;

/**
 * This is the model class for table "{{%dynamic}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $content
 * @property int $direction 动态类型：0主动动态，1被动动态
 * @property int $retweet_id 转发动态原始ID
 * @property int $status
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at
 */
class TopicSearch extends \common\logics\TopicLogic {

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        $query = static::find()->where([
            'deleted_at' => 0,
        ])->orderBy('weight desc');
        $query->with(['user']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        return $dataProvider;
    }

    /**
     * 话题详情
     * @param $params
     */
    public function detail($params=[]){
        $condition = [];
        if (isset($params['topic_id'])) {
            $condition['id'] = $params['topic_id'];
        } else if (isset($params['topic_content'])) {
            $condition['content'] = trim($params['topic_content'], '#');
        } else{
            throw new Exception('参数topic_content , topic_id 必须有一个存在 ');
        }

        $topic = static::find()->where(['or',$condition])->one();
        $topic->views += 1;
        $topic->save();

        return $topic->toArray([
            'id',
            'pic',
            'content',
            'is_official',
            'join_nums',
            'views',
            'time',
            'created_at'
        ]);
    }

}
